package q151_reverseWords;

import java.util.Arrays;

public class Solution_1 {
    public static void main(String[] args) {
        String a = "  hello world  ";

        String[] b = a.split("\\s+");
        System.out.println(Arrays.asList(b));
        System.out.println(b[1]);
    }
    public String reverseWords(String s) {

        // 先去除字符串前面所有的空格
        while (s.length() != 0 && s.charAt(0) == ' ') {
            s = s.substring(1);
        }

        StringBuilder res = new StringBuilder();
        // 然后拆分字符串
        String[] splitWords = s.split("\\s+");
        int p1 = 0, p2 = splitWords.length - 1;
        // 头尾依次对调
        while (p2 > p1) {
            String temp = splitWords[p1];
            splitWords[p1] = splitWords[p2];
            splitWords[p2] = temp;

            p1 ++;
            p2 --;
        }
        for (String splitWord : splitWords) {
            res.append(splitWord).append(" ");
        }
        return res.substring(0, res.length() - 1);
    }
}
